package com.goktech.olala.client.controller.order;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.goktech.olala.client.controller.basic.BasicController;
import com.goktech.olala.core.req.ReqOrder;
import com.goktech.olala.core.req.ReqOrderDetail;
import com.goktech.olala.core.resp.*;
import com.goktech.olala.core.service.ICtmInfoService;
import com.goktech.olala.core.service.IGoodsService;
import com.goktech.olala.core.service.IOrderDetailService;
import com.goktech.olala.core.service.IOrderShopCartService;
import com.goktech.olala.utils.RMBUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * @author wyn
 */
@Controller
@RequestMapping("/orderApi")
public class OrderDetailController extends BasicController {
    private static final String RESP_DATA= "respData";
    private static final String  LOGIN_USER_ID = "LoginUserId";

    @Autowired
    IOrderDetailService orderDetailService;

    @Autowired
    IOrderShopCartService shopCartService;

    @Autowired
    ICtmInfoService iCtmInfoService;

    @Autowired
    IGoodsService goodsService;

    /**
     * 立即购买
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/settleOrder.do")
    @ResponseBody
    public ModelAndView settleOrder(HttpServletRequest request, HttpServletResponse response) {
        ModelAndView mv = new ModelAndView("home/pay");
        String customerId = (String)request.getSession().getAttribute(LOGIN_USER_ID);
        String realBuyPrice = request.getParameter("realBuyPrice");
        String goodsId = request.getParameter("goodsId");
        String goodsName = request.getParameter("goodsName");
        String shopPrice = request.getParameter("shopPrice");
        String goodsAmount = request.getParameter("goodsAmount");
        String goodsAttr = request.getParameter("goodsAttr");

        try {
            List<RespBuyInfoVo> respBuyInfoVoList = new ArrayList<>();
            RespBuyInfoVo respBuyInfoVo = new RespBuyInfoVo();
            respBuyInfoVo.setGoodsId(goodsId);
            respBuyInfoVo.setGoodsName(goodsName);
            respBuyInfoVo.setGoodsAttr(goodsAttr);
            int price = Integer.parseInt(RMBUtil.changeY2F(realBuyPrice));
            int amount = Integer.parseInt(goodsAmount);
            respBuyInfoVo.setOrderMoney(price*amount+"");
            respBuyInfoVo.setPayMoney(price*amount+"");
            respBuyInfoVo.setGoodsAmount(amount);
            respBuyInfoVo.setGoodsPrice(shopPrice);
            respBuyInfoVo.setCustomerId(customerId);

            respBuyInfoVoList.add(respBuyInfoVo);
            List<RespConsigneeVo> respConsigneeVoList = iCtmInfoService.queryCustomerConsignee(customerId);
            mv.addObject("buyGoodsList", respBuyInfoVoList);
            mv.addObject("consigneeVoList", respConsigneeVoList);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return mv;
    }

    /**
     * 购物车结算
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/settleShopCart.do")
    @ResponseBody
    public ModelAndView settleShopCart(HttpServletRequest request, HttpServletResponse response) {
        ModelAndView mv = new ModelAndView("home/pay");
        String customerId = (String)request.getSession().getAttribute(LOGIN_USER_ID);
        if(StringUtils.isBlank(customerId)){
            mv.setViewName("home/login");
            return mv;
        }
        String shopCartIdArrStr = request.getParameter("shopCartIdArr");
        String amountArrStr = request.getParameter("amountArr");

        try {
            List<RespBuyInfoVo> respBuyInfoVoList = new ArrayList<>();
            if(StringUtils.isNotBlank(shopCartIdArrStr) && StringUtils.isNotBlank(amountArrStr)){
                String[] shopCartIdArr = shopCartIdArrStr.split(",");
                String[] amountArr = amountArrStr.split(",");
                for(int i=0;i<shopCartIdArr.length;i++){
                    String shopCartId = shopCartIdArr[i];
                    int amount = Integer.parseInt(amountArr[i]);
                    RespBuyInfoVo respBuyInfoVo = new RespBuyInfoVo();
                    RespShopCartVo respShopCartVo = shopCartService.queryShopCartById(shopCartId);
                    respBuyInfoVo.setGoodsId(respShopCartVo.getGoodsId());
                    respBuyInfoVo.setGoodsName(respShopCartVo.getGoodsName());
                    respBuyInfoVo.setGoodsAttr(respShopCartVo.getGoodsAttr());
                    String realBuyPrice = respShopCartVo.getRealBuyPrice();
                    int price = Integer.parseInt(RMBUtil.changeY2F(realBuyPrice));
                    respBuyInfoVo.setOrderMoney(RMBUtil.changeF2Y(price*amount+""));
                    respBuyInfoVo.setPayMoney(RMBUtil.changeF2Y(price*amount+""));
                    respBuyInfoVo.setGoodsAmount(amount);
                    respBuyInfoVo.setGoodsPrice(realBuyPrice);
                    respBuyInfoVo.setCustomerId(customerId);

                    respBuyInfoVoList.add(respBuyInfoVo);
                }
            }
            List<RespConsigneeVo> respConsigneeVoList = iCtmInfoService.queryCustomerConsignee(customerId);
            mv.addObject("buyGoodsList", respBuyInfoVoList);
            mv.addObject("consigneeVoList", respConsigneeVoList);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return mv;
    }

    /**
     * 提交订单
     *
     * @param request
     * @param response
     * @return
     */
    @PostMapping(path = "/unifiedOrder.do")
    @ResponseBody
    public String unifiedOrder(HttpServletRequest request, HttpServletResponse response) {
        String customerId = (String)request.getSession().getAttribute(LOGIN_USER_ID);
        String orderMoney = request.getParameter("orderMoney");
        String goodsIdArrStr = request.getParameter("goodsIdArr");
        String amountArrStr = request.getParameter("amountArr");
        String priceArrStr = request.getParameter("priceArr");

        try {
            ReqOrder reqOrder = new ReqOrder();
            if(StringUtils.isNotBlank(goodsIdArrStr)){
                List<ReqOrderDetail> reqOrderDetails = new ArrayList<>();
                ReqOrderDetail orderDetail = null;
                String[] goodsIdArr = goodsIdArrStr.split(",");
                String[] amountArr = amountArrStr.split(",");
                String[] priceArr = priceArrStr.split(",");

                for (int i=0;i<goodsIdArr.length;i++) {
                    String goodsId = goodsIdArr[i];
                    int amount = Integer.parseInt(amountArr[i]);
                    int price = Integer.parseInt(priceArr[i]);
                    RespGoodsVo goodsVo = goodsService.queryGoodsById(goodsId);

                    orderDetail = new ReqOrderDetail();
                    orderDetail.setGoodsId(goodsId);
                    orderDetail.setGoodsSn(goodsVo.getGoodsSn());
                    orderDetail.setGoodsPrice(price);
                    orderDetail.setGoodsName(goodsVo.getGoodsName());
                    orderDetail.setQuantity(amount);
                    orderDetail.setShopPrice(goodsVo.getShopPrice());
                    orderDetail.setMarketPrice(goodsVo.getMarketPrice());
                    orderDetail.setCostPrice(goodsVo.getCostPrice());
                    orderDetail.setPromotePrice(goodsVo.getPromotePrice());

                    reqOrderDetails.add(orderDetail);
                }
                reqOrder.setOrderDetails(reqOrderDetails);
            }
            reqOrder.setPayMoney(Integer.valueOf(orderMoney));
            reqOrder.setOrderMoney(Integer.valueOf(orderMoney));
            reqOrder.setCustomerId(customerId);
            orderDetailService.saveOrder(reqOrder);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "success";
    }

    /**
     * 删除当前商品
     * @param request
     */
    @PostMapping(path = "/delete.do")
    @ResponseBody
    public void deleteByGoodsId(HttpServletRequest request) {
        Integer orderId = Integer.parseInt(request.getParameter("customerId"));
        try {
            orderDetailService.deleteById(orderId);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 查询订单
     * @param request
     * @param sEcho
     * @param iDisplayStart
     * @param iDisplayLength
     * @return
     */
    @PostMapping(path = "/queryOrderList.do")
    @ResponseBody
    public ModelMap queryMemberLoginLog(HttpServletRequest request, Integer sEcho,
                                        Integer iDisplayStart, Integer iDisplayLength) {
        ModelMap resultMap = new ModelMap();
        Integer respCode = 10000;
        String respMsg = "查询成功!";
        JSONObject respData = new JSONObject();
        try {
            JSONObject params = super.reqParamsFormat(request);
            ReqOrder reqOrder = buildOrder(params);

            int pageIndex = iDisplayStart / iDisplayLength + 1;

            PageInfo<OrderResp> pageInfo = orderDetailService.queryOrders(pageIndex, iDisplayLength, reqOrder);


            if (pageInfo != null && CollectionUtils.isEmpty(pageInfo.getList())) {
                respCode = -10000;
                respMsg = "查询结果集为空!";
            }
            respData = super.respParamsFormat(respCode, respMsg, sEcho, pageInfo);
        } catch (Exception e) {
            e.printStackTrace();
            respCode = -10001;
            respMsg = e.getMessage();
            respData = super.respParamsFormat(respCode, respMsg, null);
        } finally {
            resultMap.put(RESP_DATA, respData);
        }
        return resultMap;
    }

    /**
     * 根据ID查询订单信息
     * @param request
     * @return
     */
    @RequestMapping(value = "queryOrderByKey.do")
    @ResponseBody
    public ModelMap queryOrderByPrimarykey(HttpServletRequest request) {
        ModelMap resultMap = new ModelMap();
        Integer respCode = 10000;
        String respMsg = "查询成功!";

        JSONObject respData = new JSONObject();
        try {
            JSONObject params = super.reqParamsFormat(request);
            Integer orderId = params.getInteger("orderId");

            if (orderId == null) {
                respCode = -10002;
                respMsg = "输入参数错误！";

                respData = super.respParamsFormat(respCode, respMsg, null);
                resultMap.put(RESP_DATA, respData);
                return resultMap;
            }
            OrderResp orderResp = orderDetailService.queryOrderById(orderId);

            if (orderResp == null) {
                respCode = -10000;
                respMsg = "查询结果集为空!";
            }

            respData = super.respParamsFormat(respCode, respMsg, orderResp);
        } catch (Exception e) {
            e.printStackTrace();
            respCode = -10001;
            respMsg = e.getMessage();
            respData = super.respParamsFormat(respCode, respMsg, null);
        } finally {
            resultMap.put(RESP_DATA, respData);
        }
        return resultMap;
    }

    /**
     * 构建查询实体类
     * @param params
     * @return
     */
    public ReqOrder buildOrder(JSONObject params) {
        ReqOrder reqOrder = new ReqOrder();
        //订单编号
        String orderSn = params.getString("orderSn");
        //订单Id
        Integer orderId = params.getInteger("orderId");
        //订单详情表Id
        Integer orderdetailId = params.getInteger("orderdetailId");
        //订单商品Id
        String goodsId = params.getString("goodsId");
        //退货单编号
        String refundOrder = params.getString("refundOrder");
        //商品名称
        String goodsName = params.getString("goodsName");
        //客户ID
        String customerId = params.getString("customerId");
        //支付类型
        Integer payType = params.getInteger("payType");
        //支付时间
        String payTime = params.getString("payTime");
        //订单金额
        Integer orderMoney = params.getInteger("orderMoney");
        //优惠金额
        Integer districtMoney = params.getInteger("districtMoney");
        //支付金额
        Integer payMoney = params.getInteger("payMoney");
        //下单时间
        String orderTime = params.getString("orderTime");
        //收货时间
        String receiveTime = params.getString("receiveTime");
        //订单积分
        Integer orderPoint = params.getInteger("orderPoint");
        //订单状态
        Integer orderStatus = params.getInteger("orderStatus");
        //最后修改时间
        String modifiedTime = params.getString("modifiedTime");
        //订单流水号
        String transationNo = params.getString("transationNo");
        //配送费用
        Integer delivFee = params.getInteger("delivFee");
        //配送日期
        String delivDate = params.getString("delivDate");
        //退货人
        String custName = params.getString("custName");
        //退货时间
        String refundDate = params.getString("refundDate");
        //退货状态
        Integer refundStatue = params.getInteger("refundStatue");
        //退货数量
        Integer quanTity = params.getInteger("quanTity");

        reqOrder.setOrderSn(orderSn);
        reqOrder.setOrderId(orderId);
        reqOrder.setOrderDetailId(orderdetailId);
        reqOrder.setGoodsId(goodsId);
        reqOrder.setRefundOrder(refundOrder);
        reqOrder.setGoodsName(goodsName);
        reqOrder.setCustName(custName);
        reqOrder.setCustomerId(customerId);
        reqOrder.setPayTime(payTime);
        reqOrder.setPayType(payType);
        reqOrder.setPayMoney(orderMoney);
        reqOrder.setDistrictMoney(districtMoney);
        reqOrder.setPayMoney(payMoney);
        reqOrder.setOrderTime(orderTime);
        reqOrder.setReceiveTime(receiveTime);
        reqOrder.setOrderPoint(orderPoint);
        reqOrder.setOrderStatus(orderStatus);
        reqOrder.setModifiedTime(modifiedTime);
        reqOrder.setTransationNo(transationNo);
        reqOrder.setDelivFee(delivFee);
        reqOrder.setDelivDate(delivDate);
        reqOrder.setRefundDate(refundDate);
        reqOrder.setRefundStatue(refundStatue);
        reqOrder.setQuanTity(quanTity);

        return reqOrder;
    }
}
